# -*- coding:utf-8 -*-

from flask import Flask, render_template, request
from constants import QINIU_ACCESS_KEY, QINIU_SECRET_KEY, QINIU_BUCKET_NAME
from qiniu import Auth, put_data
import datetime
import uuid
import os
import mimetypes

app = Flask(__name__)


def upload_file(filename, data):
    _, ext = os.path.splitext(filename)
    key = str(datetime.date.today()) + "-" + str(uuid.uuid4()) + ext
    mime_type = mimetypes.MimeTypes().guess_type(filename)[0]

    qiniu_svc = Auth(QINIU_ACCESS_KEY, QINIU_SECRET_KEY)
    upload_token = qiniu_svc.upload_token(QINIU_BUCKET_NAME, key, 3600)
    ret, info = put_data(up_token=upload_token, key=key, data=data, mime_type=mime_type)

    print('filename: {}'.format(filename))
    print('data info: {}, ret: {}'.format(info, ret))

    if ret is None:
        return ''

    return 'https://daan.dreamcapsule.top/' + ret['key']


@app.route('/', methods=['GET', 'POST'])
def upload():
    if request.method == 'GET':
        return render_template('upload.html')

    if 'file' not in request.files:
        return 'data not in file'

    file = request.files['file']
    file_url = upload_file(file.filename, file.read())
    return {'file_url': file_url, 'message': 'ok'}


if __name__ == '__main__':
    app.run('127.0.0.1', '8090')
